import '../css/login.module.css'
import '../App.css'
import { useState, useEffect } from 'react'
import type { ReactNode } from 'react'
import { SearchBar, Swiper, Toast, TabBar } from 'antd-mobile'
import { SetOutline } from 'antd-mobile-icons'
import right from '../assets/箭头-右.png'
import big from '../assets/xiao.png'  // 已添加状态的图标
import add from '../assets/add.png'   // 未添加状态的图标
import shopping from '../assets/shopping.png'
import { home, shoppingAdd, shoppingEdit, shoppingList } from '../api/index.ts'
import { path } from '../config/index.ts'
import { useNavigate, useLocation } from 'react-router-dom'
import {
    AppOutline,
    UnorderedListOutline,
    UserOutline,
} from 'antd-mobile-icons'

export default function Index() {
    const [data, setData] = useState<any>(null);
    const [addedCommodities, setAddedCommodities] = useState<Set<string>>(new Set()); // 跟踪已添加的商品ID
    const [cartData, setCartData] = useState<any[]>([]); // 存储购物车数据
    const navigate = useNavigate();
    const location = useLocation();

    useEffect(() => {
        const fetchHomeData = async () => {
            try {
                const res = await home({});
                console.log('接口返回:', res.data);
                setData(res.data);
            } catch (error) {
                console.error('home接口请求失败:', error);
                Toast.show('数据加载失败，请稍后重试');
            }
        };

        // 初始化时获取购物车数据，设置已添加商品状态
        const initCartAndAddedCommodities = async () => {
            const userId = localStorage.getItem('uid');
            if (!userId) return;

            try {
                await fetchCartList(userId);
            } catch (error) {
                console.error('初始化购物车状态失败:', error);
            }
        };

        fetchHomeData();
        initCartAndAddedCommodities();
    }, []);

    // 重新请求购物车列表的函数
    const fetchCartList = async (userId: string) => {
        try {
            const cartListRes = await shoppingList({ id: userId });
            const cartList = cartListRes.data || [];
            setCartData(cartList);

            // 将购物车中已存在的商品ID添加到集合中
            const addedIds = new Set<string>();
            cartList.forEach((item: any) => {
                if (item.commodity && item.commodity.length > 0) {
                    addedIds.add(item.commodity[0].id);
                }
            });

            setAddedCommodities(addedIds);
        } catch (error) {
            console.error('获取购物车列表失败:', error);
            Toast.show('获取购物车列表失败');
        }
    };

    const [icon, setIcon] = useState<ReactNode | null>(<SetOutline />)

    // 处理轮播图数据
    const bannerItems = data?.banner?.map((item: any, index: number) => (
        <Swiper.Item key={index}>
            <div
                className='content'
                style={{ backgroundImage: `url(${path + item.banner})`, backgroundSize: 'cover', backgroundPosition: 'center' }}>
            </div>
        </Swiper.Item>
    ))

    // 处理下方总览区域分类数据
    const classifyItems = data?.classify?.map((item: any, index: number) => (
        <div className='cen' key={index}>
            <img src={path + item.icon} alt={item.title} className='wid' />
            <span>{item.title}</span>
        </div>
    ))

    const tabs = [
        {
            key: '/',
            title: '首页',
            icon: <AppOutline />,
            onClick: () => navigate('/')
        },
        {
            key: '/category',
            title: '分类',
            icon: <UnorderedListOutline />,
            onClick: () => navigate('/category')
        },
        {
            key: '/cart',
            title: '购物车',
            icon: (active: boolean) => <img src={active ? shopping : shopping} alt="" style={{ width: '24px', height: '24px' }} />,
            onClick: () => navigate('/cart')
        },
        {
            key: '/mine',
            title: '我的',
            icon: <UserOutline />,
            onClick: () => navigate('/mine')
        },
    ]

    // 根据当前路径确定activeKey
    const activeKey = tabs.find(tab => location.pathname === tab.key)?.key || '/';

    // 修改添加购物车方法
    const handleAddToCart = async (commodityId: string) => {
        // 从本地存储获取user_id
        const userId = localStorage.getItem('uid');
        if (!userId) {
            console.log('用户ID获取失败，请重新登录');
            Toast.show('用户ID获取失败，请重新登录');
            return;
        }

        try {
            // 查找购物车中是否已存在该商品
            const existingCartItem = cartData.find((item: any) =>
                item.commodity && item.commodity.some((comm: any) => comm.id === commodityId)
            );

            if (existingCartItem) {
                // 存在，调用编辑接口，数量加一
                const editRes = await shoppingEdit({
                    id: existingCartItem.id, // 购物车id
                    num: (parseInt(existingCartItem.num) + 1).toString() // 数量加一
                });
                if (editRes.code === 1) {
                    console.log('编辑购物车成功');
                    Toast.show('购物车商品数量加一');
                    // 重新请求购物车列表
                    await fetchCartList(userId);
                } else {
                    console.error(`编辑购物车失败：${editRes.message || '未知错误'}`);
                    Toast.show('编辑购物车失败');
                }
            } else {
                // 不存在，调用新增接口
                const addRes = await shoppingAdd({
                    user_id: userId,
                    commodity_id: commodityId,
                    num: '1'
                });
                console.log('shoppingAdd 接口返回', addRes);
                if (addRes.code === 1) {
                    console.log('添加购物车成功');
                    Toast.show('已添加到购物车');
                    // 重新请求购物车列表
                    await fetchCartList(userId);
                } else {
                    console.error(`添加购物车失败：${addRes.message || '未知错误，或接口未返回购物车项id'}`);
                    Toast.show('添加购物车失败');
                }
            }
        } catch (error) {
            console.error('购物车操作请求失败:', error);
            Toast.show('购物车操作失败，请稍后重试');
        }
    };

    // 跳转到商品详情页
    const navigateToDetail = (product: any, productId: string) => {
        sessionStorage.setItem('dataList', JSON.stringify(product));
        navigate(`/xiangqing/${productId}`);
    };

    return (
        <div className='Box'>
            <div className='white'>
                <div className='p10'>
                    <SearchBar
                        placeholder='请输入内容'
                    />
                    <div className='search'>搜索</div>
                </div>
                {/* 轮播图 */}
                <div className='m10'>
                    {data?.banner && bannerItems ? (
                        <Swiper
                            loop
                            autoplay
                            style={{
                                '--border-radius': '8px',
                            }}>
                            {bannerItems}
                        </Swiper>
                    ) : (
                        <div className='loading-swiper'>轮播图加载中...</div>
                    )}
                    <div className='m10'>
                        {data?.classify && classifyItems ? (
                            <div className='display'>
                                {classifyItems}
                            </div>
                        ) : (
                            <div className='loading-classify'>分类加载中...</div>
                        )}
                    </div>
                </div>
            </div>
            {/* 热门榜单 */}
            <div className='white'>
                <div className='h10'></div>
                <div className='end'>
                    <div className='center'>
                        <img src="https://img.xiaopiu.com/userImages/img17104618ac1522220.png" alt="热门榜单图标" className='width' />
                        <span>热门榜单</span>
                    </div>
                    <div className='center white radiu'>
                        <span>更多</span>
                        <img src={right} alt="更多箭头" className='icon' />
                    </div>
                </div>
                <div className='display'>
                    <div className='cen'>
                        <img src="https://img.xiaopiu.com/userImages/img17100618ac142d428.jpg" alt="母婴热卖商品" className='big' />
                        <p>母婴热卖榜</p>
                        <span className='red'>￥899.00</span>
                    </div>
                    <div className='cen'>
                        <img src="https://img.xiaopiu.com/userImages/img17102718ac147c1e0.jpg" alt="电器热卖商品" className='big' />
                        <p>电器热卖榜</p>
                        <span className='red'>￥1249.00</span>
                    </div>
                    <div className='cen'>
                        <img src="https://img.xiaopiu.com/userImages/img17103118ac14a4668.jpg" alt="食品热卖商品" className='big' />
                        <p>食品热卖榜</p>
                        <span className='red'>￥59.00</span>
                    </div>
                </div>
                <div className='h10'></div>
            </div>
            {/* 猜你喜欢 */}
            <div className='white'>
                <div className='display h20'>
                    <span style={{ fontSize: '15px' }}>猜你喜欢</span>
                    <span>美妆</span>
                    <span>男装</span>
                    <span>女装</span>
                    <span>食品</span>
                    <span>电器</span>
                </div>
            </div>
            {/* 瀑布布局 */}
            <div className="column">
                {data?.commodity?.map((item: any, index: number) => (
                    <div className="list_box" key={index}>
                        <div className="list_item" onClick={() => navigateToDetail(item, item.id)}>
                            <img
                                src={path + item.image || 'https://img.xiaopiu.com/userImages/img17095018ac1206f78.jpg'}
                                alt={item.title}
                            />
                            <div className='m7'>
                                {item.title}
                            </div>
                        </div>
                        <div className="icon_img">
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <span className='red'>￥{item.price}</span>
                            </div>
                            <div>
                                {/* 根据商品是否已添加，显示不同图标 */}
                                <img
                                    src={addedCommodities.has(item.id) ? big : add}
                                    alt={addedCommodities.has(item.id) ? "已添加" : "添加"}
                                    className='width'
                                    onClick={() => handleAddToCart(item.id)}
                                />
                            </div>
                        </div>
                    </div>
                ))}
            </div>
            <div style={{ height: '80px' }}></div>
            {/* 底部导航栏 */}
            <TabBar activeKey={activeKey} onChange={(key) => {
                const tab = tabs.find(tab => tab.key === key);
                if (tab) {
                    tab.onClick();
                }
            }}>
                {tabs.map(item => (
                    <TabBar.Item
                        key={item.key}
                        icon={item.icon}
                        title={item.title}
                        onClick={item.onClick}
                    />
                ))}
            </TabBar>
        </div>
    )
}